//
//  FRQResellerGalleryViewController.m
//  FRQBluetoothKit_Example
//
//  Created by admin on 2023/10/22.
//  Copyright © 2023 xuchunhai. All rights reserved.
//

#import "FRQResellerGalleryDealerViewController.h"
#define KCellID @"MonthCardPayViewsID"
#define KHedderID @"MonthCardPayViewsHedderID"
#define KFooterID @"MonthCardPayViewsFooterID"
#import "ResellerGalleryDealerViews.h"
#import "ResellerGalleryCells.h"
#import "YSHYClipViewController.h"
#import "FRQCroppedImageViewController.h"
#import "SVGKImage.h"
#import "SVGKit.h"
@interface FRQResellerGalleryDealerViewController ()<ClipViewControllerDelegate>
@property (nonatomic,strong) ResellerGalleryDealerViews *resellerGalleryView;
@property (nonatomic,strong) NSArray *arrImageList;
@property (nonatomic,strong) NSMutableArray *arrSelectIndex;
@property (nonatomic,assign) NSInteger pageNum;
@property (nonatomic,assign) NSInteger totalPage;
@end

@implementation FRQResellerGalleryDealerViewController
///user/nft/list
-(void)userNftList:(HJHttpRequest)callback{
    
    NSDictionary *dic=@{@"pageNum":[NSString stringWithFormat:@"%ld",self.pageNum],
                        @"pageSize":@12
    };
    NSString *urlName;
    urlName=@"app/sys/user/nft/list";
    [skNetTools skGETWithURL:[NSString stringWithFormat:@"%@%@",skURL,urlName] parameters:dic cachePolicy:0 callback:^(id  _Nonnull responseObject, NSError * _Nonnull error) {
        self.arrSelectIndex=[[NSMutableArray alloc] init];
        NSLog(@"数据=%@",responseObject);
        skNetModel *model=[skNetModel mj_objectWithKeyValues:responseObject];
//        [SkToast SkToastShow:model.msg];
        if(model.code==200){
            self.arrImageList=[model.data objectForKey:@"data"];
            self.totalPage=[[model.data objectForKey:@"totalPage"] intValue];
            [self.collectionView reloadData];
        }
        callback(responseObject,error);
    }];
}

-(void)deleteWallet:(NSInteger)type{
    NSMutableArray *arrlist=[[NSMutableArray alloc] init];
    if(type==0){//全部删除
        self.arrSelectIndex=[[NSMutableArray alloc] init];
        for (int i =0; i<self.arrImageList.count; ++i) {
            NSString *selectIndex=[NSString stringWithFormat:@"%d",i];
            
            if([self.arrSelectIndex containsObject:selectIndex]){
                [self.arrSelectIndex removeObject:selectIndex];
            }else{
                [self.arrSelectIndex addObject:selectIndex];
            }
            [self.collectionView reloadData];
        }
        return;
    }else{//删除选中部分
        for (int i =0; i<self.arrSelectIndex.count; ++i) {
            
            NSString *indexT=[self.arrSelectIndex objectAtIndex:i];
            
            NSDictionary *dic=[self.arrImageList objectAtIndex:[indexT intValue]];
            
            NSString *walletId=[NSString stringWithFormat:@"%@",[dic objectForKey:@"id"]];
            [arrlist addObject:walletId];
        }
    }
    
    NSDictionary *dic=@{@"nftIds":arrlist};
    
    [skNetTools skPOSTWithURL:[NSString stringWithFormat:@"%@%@",skURL,@"app/sys/user/nft/remove"] parameters:dic cachePolicy:0 callback:^(id  _Nonnull responseObject, NSError * _Nonnull error) {
        NSLog(@"数据=%@",responseObject);
        skNetModel *model=[skNetModel mj_objectWithKeyValues:responseObject];
        if(model.code==200){
            [self userNftList:^(id  _Nonnull responseObject, NSError * _Nonnull error) {
                
            }];
        }else{
            [SkToast SkToastShow:model.msg];
        }
    }];
}
-(ResellerGalleryDealerViews *)resellerGalleryView{
    if (nil==_resellerGalleryView) {
        _resellerGalleryView=skXibView(@"ResellerGalleryDealerViews");
        @weakify(self)
        [[_resellerGalleryView.btnSelect rac_signalForControlEvents:(UIControlEventTouchUpInside)] subscribeNext:^(__kindof UIControl * _Nullable x) {
            @strongify(self)
            [self deleteWallet:0];
        }];
        [[_resellerGalleryView.btnDelete rac_signalForControlEvents:(UIControlEventTouchUpInside)] subscribeNext:^(__kindof UIControl * _Nullable x) {
            @strongify(self)
            [self deleteWallet:1];
        }];
    }
    return _resellerGalleryView;
}
#pragma mark - ClipViewControllerDelegate
-(void)ClipViewController:(YSHYClipViewController *)clipViewController FinishClipImage:(UIImage *)editImage
{
    
}
-(UICollectionView *)collectionView{
    if (nil==_collectionView) {
        
        //1.初始化layout
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
        //设置collectionView滚动方向
        [layout setScrollDirection:UICollectionViewScrollDirectionVertical];
        //设置headerView的尺寸大小
        layout.headerReferenceSize = CGSizeMake(skScreenWidth, 400);
        //设置尾部的尺寸大小
//        layout.footerReferenceSize = CGSizeMake(self.frame.size.width, 30);
        //        该方法也可以设置itemSize
        
        
        layout.itemSize =CGSizeMake((skScreenWidth-120)/3, 89);
        _collectionView=[[UICollectionView alloc] initWithFrame:self.view.bounds collectionViewLayout:layout];
        
        [self.view addSubview:_collectionView];
        [_collectionView setBackgroundColor:[UIColor groupTableViewBackgroundColor]];
        
        [_collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(self.mas_topLayoutGuide).offset(42);
            make.left.mas_equalTo(39);
            make.right.mas_equalTo(-39);
            make.height.mas_equalTo(450);
        }];
        //3.注册collectionViewCell
        //注意，此处的ReuseIdentifier 必须和 cellForItemAtIndexPath 方法中 一致 均为 cellId
        [_collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:KCellID];
        //注册headerView  此处的ReuseIdentifier 必须和 cellForItemAtIndexPath 方法中 一致  均为reusableView
        [_collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:KHedderID];
        
        [_collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:KFooterID];
//        _collectionView.bounces = NO;
        //4.设置代理
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
    }
    return _collectionView;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.arrSelectIndex=[[NSMutableArray alloc] init];
    self.pageNum=1;
    self.title=@"Remove NFTs";
    [self.view addSubview:self.resellerGalleryView];
    // Do any additional setup after loading the view.
    [self.collectionView reloadData];
    
    self.collectionView.backgroundColor=skUIColorFromRGB(0x1c1f2a);
    [self userNftList:^(id  _Nonnull responseObject, NSError * _Nonnull error) {
        
    }];
    
    [self SetupRightZLingItem:@"refresh_ico_gallery" isZLingImage:YES];
    
    self.collectionView.mj_header=[MJRefreshNormalHeader headerWithRefreshingBlock:^{
        self.pageNum=1;
        [self userNftList:^(id  _Nonnull responseObject, NSError * _Nonnull error) {
            [self.collectionView.mj_header endRefreshing];
        }];
    }];
    self.collectionView.mj_footer = [MJRefreshBackNormalFooter  footerWithRefreshingBlock:^{
        if(self.totalPage>self.pageNum){
            self.pageNum++;
        }
        [self userNftList:^(id  _Nonnull responseObject, NSError * _Nonnull error) {
            [self.collectionView.mj_footer endRefreshing];
        }];
        
    }];
}
- (void)BtnRightZLingAction:(UIButton *)sender{
    self.pageNum=1;
    [self userNftList:^(id  _Nonnull responseObject, NSError * _Nonnull error) {
        
    }];
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/
#pragma mark mark - 代理方法UICollectionReusableView
#pragma mark collectionView代理方法
//返回section个数
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}

//每个section的item个数
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.arrImageList.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:KCellID forIndexPath:indexPath];
    
    for (UIView *view in cell.contentView.subviews) {
        if (view) {
            [view removeFromSuperview];
        }
    }
    ResellerGalleryCells *view=skXibView(@"ResellerGalleryCells");
    view.btnSelect.hidden=YES;
    NSDictionary *dic=self.arrImageList[indexPath.row];
    NSString *imageName=[dic objectForKey:@"imageUrl"];
    [view.imageIcon sd_setImageWithURL:[NSURL URLWithString:imageName] completed:^(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {
        if([imageName containsString:@".svg"]){
            view.imageIcon.image=[self svgImageNamed:imageName size:CGSizeMake(200, 200)];
        }
    }];
    NSString *selectIndex=[NSString stringWithFormat:@"%ld",(long)indexPath.row];
    if([self.arrSelectIndex containsObject:selectIndex]){
        view.btnSelect.hidden=NO;
    }else{
        view.btnSelect.hidden=YES;
    }
    
    [cell.contentView addSubview:view];
    
    return cell;
}

- (UIImage *)svgImageNamed:(NSString *)name size:(CGSize)size {
    SVGKImage *svgImage = [SVGKImage imageWithContentsOfURL:[NSURL URLWithString:name]];
    svgImage.size = size;
    UIImage *image=svgImage.UIImage;
    return image;
}
//设置每个item的尺寸
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    return CGSizeMake((skScreenWidth-120)/3, 89);
}

//footer的size
//- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section
//{
//    return CGSizeMake(10, 10);
//}

//header的size
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section
{
    return CGSizeMake(skScreenWidth-90, 0);
}

//设置每个item的UIEdgeInsets
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(1, 7, 1, 7);
}

//设置每个item水平间距
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section
{
    return 5;
}


//设置每个item垂直间距
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section
{
    return 15;
}


//通过设置SupplementaryViewOfKind 来设置头部或者底部的view，其中 ReuseIdentifier 的值必须和 注册是填写的一致，本例都为 “reusableView”
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    if (kind ==UICollectionElementKindSectionHeader){
        
        UICollectionReusableView *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:KHedderID forIndexPath:indexPath];
        
        for (UIView *view in headerView.subviews) {
            if (view) {
                [view removeFromSuperview];
            }
        }
        
        return headerView;
    }
    
    if (kind ==UICollectionElementKindSectionFooter) {
        UICollectionReusableView *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:KFooterID forIndexPath:indexPath];
        
        
        
        return headerView;
    }
    return nil;
}

//点击item方法
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *selectIndex=[NSString stringWithFormat:@"%ld",(long)indexPath.row];
    
    if([self.arrSelectIndex containsObject:selectIndex]){
        [self.arrSelectIndex removeObject:selectIndex];
    }else{
        [self.arrSelectIndex addObject:selectIndex];
    }
    [self.collectionView reloadData];
}

@end
